<template>
  <div class="announcements section-container">
    <div class="page-header">
      <h2 class="page-title">公告管理</h2>
      <p class="page-subtitle">发布、管理和查看公司内部的各类通知、规章制度和活动安排</p>
    </div>

    <div class="action-bar">
      <el-button type="primary" @click="showAddDialog" class="action-btn">发布公告</el-button>
    </div>

    <div class="content-section">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="标题">
            <el-input v-model="searchForm.title" placeholder="公告标题" clearable />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="searchForm.type" placeholder="公告类型" clearable>
              <el-option :value="1" label="普通通知" />
              <el-option :value="2" label="规章制度" />
              <el-option :value="3" label="活动安排" />
              <el-option :value="4" label="紧急事项" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.active" placeholder="公告状态" clearable>
              <el-option :value="true" label="有效" />
              <el-option :value="false" label="全部" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="announcements" style="width: 100%" v-loading="loading">
        <el-table-column prop="title" label="标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">
              {{ getTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="importance" label="重要程度" width="120">
          <template #default="{ row }">
            <el-tag :type="getImportanceTag(row.importance)">
              {{ getImportanceName(row.importance) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="生效时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="失效时间" width="180">
          <template #default="{ row }">
            {{ row.endTime ? formatDateTime(row.endTime) : '永久有效' }}
          </template>
        </el-table-column>
        <el-table-column prop="isTop" label="是否置顶" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isTop === 1 ? 'danger' : 'info'">
              {{ row.isTop === 1 ? '已置顶' : '未置顶' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="260">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">查看</el-button>
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button 
              v-if="row.isTop === 0" 
              link 
              type="warning" 
              @click="handleTop(row)"
            >
              置顶
            </el-button>
            <el-button 
              v-else 
              link 
              type="info" 
              @click="handleUntop(row)"
            >
              取消置顶
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑公告' : '发布公告'"
      width="700px"
      :modal-append-to-body="false"
      :append-to-body="true"
      align-center
      class="announcement-dialog"
    >
      <el-scrollbar max-height="60vh">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="announcement-form"
        >
          <el-form-item label="公告标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入公告标题" />
          </el-form-item>
          <el-form-item label="公告类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择公告类型" style="width: 100%">
              <el-option :value="1" label="普通通知" />
              <el-option :value="2" label="规章制度" />
              <el-option :value="3" label="活动安排" />
              <el-option :value="4" label="紧急事项" />
            </el-select>
          </el-form-item>
          <el-form-item label="重要程度" prop="importance">
            <el-select v-model="form.importance" placeholder="请选择重要程度" style="width: 100%">
              <el-option :value="1" label="普通" />
              <el-option :value="2" label="重要" />
              <el-option :value="3" label="非常重要" />
            </el-select>
          </el-form-item>
          <el-form-item label="生效时间" prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              placeholder="选择生效时间"
              style="width: 100%"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="失效时间" prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="选择失效时间（不填则永久有效）"
              style="width: 100%"
              clearable
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="公告内容" prop="content">
            <el-input
              v-model="form.content"
              type="textarea"
              :rows="10"
              placeholder="请输入公告内容"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看公告详情 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="公告详情"
      width="700px"
      :modal-append-to-body="false"
      :append-to-body="true"
      align-center
      class="view-dialog"
    >
      <div v-if="currentAnnouncement" class="announcement-detail">
        <h2 class="announcement-title">{{ currentAnnouncement.title }}</h2>
        <div class="announcement-meta">
          <span class="meta-item">
            类型：<el-tag :type="getTypeTag(currentAnnouncement.type)">{{ getTypeName(currentAnnouncement.type) }}</el-tag>
          </span>
          <span class="meta-item">
            重要程度：<el-tag :type="getImportanceTag(currentAnnouncement.importance)">{{ getImportanceName(currentAnnouncement.importance) }}</el-tag>
          </span>
          <span class="meta-item">
            发布时间：{{ formatDateTime(currentAnnouncement.createTime) }}
          </span>
        </div>
        <div class="announcement-validity">
          <span>生效时间：{{ formatDateTime(currentAnnouncement.startTime) }}</span>
          <span>失效时间：{{ currentAnnouncement.endTime ? formatDateTime(currentAnnouncement.endTime) : '永久有效' }}</span>
        </div>
        <div class="announcement-content">
          <div v-html="formatContent(currentAnnouncement.content)"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../utils/request'

const announcements = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const currentAnnouncement = ref(null)

const searchForm = ref({
  title: '',
  type: null,
  active: true
})

const form = ref({
  title: '',
  content: '',
  publisherId: 1, // 默认发布者ID，实际应用中应当使用当前登录用户的ID
  type: 1,
  importance: 1,
  startTime: new Date(),
  endTime: null,
  isTop: 0
})

const rules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { max: 100, message: '公告标题长度不能超过100个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择公告类型', trigger: 'change' }
  ],
  importance: [
    { required: true, message: '请选择重要程度', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择生效时间', trigger: 'change' }
  ]
}

// 获取公告类型名称
const getTypeName = (type) => {
  const typeMap = {
    1: '普通通知',
    2: '规章制度',
    3: '活动安排',
    4: '紧急事项'
  }
  return typeMap[type] || '未知类型'
}

// 获取公告类型标签样式
const getTypeTag = (type) => {
  const typeTagMap = {
    1: '',
    2: 'success',
    3: 'warning',
    4: 'danger'
  }
  return typeTagMap[type] || 'info'
}

// 获取重要程度名称
const getImportanceName = (importance) => {
  const importanceMap = {
    1: '普通',
    2: '重要',
    3: '非常重要'
  }
  return importanceMap[importance] || '未知'
}

// 获取重要程度标签样式
const getImportanceTag = (importance) => {
  const importanceTagMap = {
    1: 'info',
    2: 'warning',
    3: 'danger'
  }
  return importanceTagMap[importance] || 'info'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString()
}

// 格式化公告内容（简单处理换行符）
const formatContent = (content) => {
  if (!content) return ''
  return content.replace(/\n/g, '<br>')
}

// 格式化日期时间为yyyy-MM-dd HH:mm:ss格式
const formatDateForServer = (date) => {
  if (!date) return null
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取公告列表
const fetchAnnouncements = async () => {
  loading.value = true
  try {
    const response = await request.get('/api/announcements', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        title: searchForm.value.title || undefined,
        type: searchForm.value.type || undefined,
        active: searchForm.value.active
      }
    })
    
    if (response.code === 200 && response.data) {
      announcements.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      announcements.value = []
      total.value = 0
      ElMessage.error(response.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取公告列表失败', error)
    ElMessage.error('获取公告列表失败')
    announcements.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 查看公告详情
const handleView = async (row) => {
  try {
    const response = await request.get(`/api/announcements/${row.id}`)
    if (response.code === 200 && response.data) {
      currentAnnouncement.value = response.data
      viewDialogVisible.value = true
    } else {
      ElMessage.error(response.msg || '获取公告详情失败')
    }
  } catch (error) {
    ElMessage.error('获取公告详情失败')
  }
}

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  form.value = {
    title: '',
    content: '',
    publisherId: 1, // 默认发布者ID
    type: 1,
    importance: 1,
    startTime: formatDateForServer(new Date()),
    endTime: null,
    isTop: 0
  }
  dialogVisible.value = true
}

// 编辑公告
const handleEdit = async (row) => {
  try {
    const response = await request.get(`/api/announcements/${row.id}`)
    if (response.code === 200 && response.data) {
      isEdit.value = true
      // 对日期时间进行处理，确保格式正确
      const announcement = { ...response.data }
      
      // 如果后端返回的是时间戳或日期对象，需要格式化为字符串
      if (announcement.startTime) {
        // 保持当前格式，如果格式已经是字符串则不变
        if (!(typeof announcement.startTime === 'string')) {
          announcement.startTime = formatDateForServer(announcement.startTime)
        }
      }
      
      if (announcement.endTime) {
        // 保持当前格式，如果格式已经是字符串则不变
        if (!(typeof announcement.endTime === 'string')) {
          announcement.endTime = formatDateForServer(announcement.endTime)
        }
      }
      
      form.value = announcement
      dialogVisible.value = true
    } else {
      ElMessage.error(response.msg || '获取公告详情失败')
    }
  } catch (error) {
    console.error('获取公告详情失败', error)
    ElMessage.error('获取公告详情失败')
  }
}

// 删除公告
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该公告吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await request.delete(`/api/announcements/${row.id}`)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        fetchAnnouncements()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 置顶公告
const handleTop = async (row) => {
  try {
    const response = await request.put(`/api/announcements/${row.id}/top`)
    if (response.code === 200) {
      ElMessage.success('置顶成功')
      fetchAnnouncements()
    } else {
      ElMessage.error(response.msg || '置顶失败')
    }
  } catch (error) {
    ElMessage.error('置顶失败')
  }
}

// 取消置顶
const handleUntop = async (row) => {
  try {
    const response = await request.put(`/api/announcements/${row.id}/untop`)
    if (response.code === 200) {
      ElMessage.success('取消置顶成功')
      fetchAnnouncements()
    } else {
      ElMessage.error(response.msg || '取消置顶失败')
    }
  } catch (error) {
    ElMessage.error('取消置顶失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 准备提交的数据，确保所有必填字段存在且格式正确
        const submitData = { ...form.value }
        
        // 确保publisherId字段存在
        if (!submitData.publisherId) {
          submitData.publisherId = 1 // 默认发布者ID
        }
        
        // 确保日期格式正确
        if (submitData.startTime && !(typeof submitData.startTime === 'string')) {
          submitData.startTime = formatDateForServer(submitData.startTime)
        }
        
        if (submitData.endTime && !(typeof submitData.endTime === 'string')) {
          submitData.endTime = formatDateForServer(submitData.endTime)
        }
        
        // 确保isTop字段存在
        if (submitData.isTop === undefined) {
          submitData.isTop = 0
        }
        
        // 调试信息：记录提交的表单数据
        console.log('提交表单数据:', JSON.stringify(submitData))
        
        let response
        if (isEdit.value) {
          response = await request.put(`/api/announcements/${submitData.id}`, submitData)
        } else {
          response = await request.post('/api/announcements', submitData)
        }
        
        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '修改成功' : '发布成功')
          dialogVisible.value = false
          fetchAnnouncements()
        } else {
          console.error('请求返回错误:', response)
          ElMessage.error(response.msg || (isEdit.value ? '修改失败' : '发布失败'))
        }
      } catch (error) {
        // 详细记录错误信息
        console.error('请求发生错误:', error)
        if (error.response) {
          console.error('错误状态码:', error.response.status)
          console.error('错误数据:', error.response.data)
        }
        ElMessage.error(isEdit.value ? '修改失败' : '发布失败')
      }
    }
  })
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchAnnouncements()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    title: '',
    type: null,
    active: true
  }
  currentPage.value = 1
  fetchAnnouncements()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAnnouncements()
}

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAnnouncements()
}

onMounted(() => {
  fetchAnnouncements()
})
</script>

<style scoped>
.announcements {
  padding: 0 24px;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-title {
  font-size: 28px;
  font-weight: 500;
  margin-bottom: 12px;
  color: var(--app-text-color);
}

.page-subtitle {
  font-size: 16px;
  color: var(--app-secondary-text);
  max-width: 700px;
  margin: 0 auto 20px;
}

.action-bar {
  margin-bottom: 24px;
  display: flex;
  gap: 12px;
}

.action-btn {
  min-width: 120px;
  height: 40px;
  font-weight: 500;
}

.search-bar {
  margin-bottom: 24px;
}

.content-section {
  margin-bottom: 40px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.announcement-list {
  margin-top: 24px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.05);
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.announcement-detail {
  padding: 24px;
}

.announcement-title {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 16px;
  text-align: center;
}

.announcement-meta {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.announcement-validity {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-bottom: 24px;
  color: var(--app-secondary-text);
}

.announcement-content {
  padding: 24px;
  background-color: #f5f7fa;
  border-radius: 12px;
  line-height: 1.6;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .action-bar {
    flex-wrap: wrap;
  }
  
  .action-btn {
    flex: 1;
    min-width: 0;
  }
}
</style> 